#include <soar.h>

#define TRANSFER_SIZE		(64)

static void sig_child(int signo)
{   
    pid_t pid;
    int stat;
    
    while((pid=waitpid(-1, &stat, WNOHANG))>0)
        printf("child %d terminated\n", pid);
    
    return;
}

int main()
{
    SOCKET sock[2]; 
    char *buf=NULL;
    pid_t pid;
    int msg_size;
    int count;

    sig_set_handler(SIGCHLD, sig_child);

	ALLOC_MULTI_RETERR(buf, char, TRANSFER_SIZE+10, -1);

    if(sock_local_pair(sock) != 0)
    {
        get_last_error(buf);
        printf("socketpair: fail %s\n", buf);
        return(-1);
    }

    if((pid=fork()) == 0)
    {
        close(sock[0]);

        while(1)
        {
            if(sock_read(sock[1], (unsigned char *)buf, &msg_size,
                        -1, WRAP))
            {
                printf("server: sock_read fail\n");
                return(-1);
            }
            if(sock_write(sock[1], (unsigned char *)buf, &msg_size,
                        -1, WRAP))
            {
                printf("server: sock_write fail\n");
                return(-1);
            }
            buf[msg_size]=ZERO;
        }

        return(0);
    }

    if(pid == -1)
    {
        printf("fork child fail\n");
        return(-1);
    }
    close(sock[1]);

    count=0;
    while(count < 1000000)
    {
        memset(buf, '0', TRANSFER_SIZE);
        msg_size=strlen(buf);
        if(sock_write(sock[0], (unsigned char *)buf, &msg_size,
                    -1, WRAP))
        {
            printf("client: sock_write fail\n");
            return(-1);
        }
        memset(buf, ZERO, sizeof(buf));
        if(sock_read(sock[0], (unsigned char *)buf, &msg_size,
                    -1, WRAP))
        {
            printf("client: sock_read fail\n");
            return(-1);
        }
        buf[msg_size]=ZERO;

        count++;
		if(count%10000 == 0)
			printf("%d finished\n", count);
    }
    //printf("msg: %s\n", buf);
    sleep(3);

    return(0);
}
